<template>
	<view class="sun-page">
		<!-- 搜索框 -->
		<view class="search-box">
			<u-search placeholder="请输入标签编码" v-model="searchText" :showAction="false" :clearabled="true" shape="round"
				bgColor="#FFFFFF" @change="onSearchChange"></u-search>
		</view>

		<!-- 状态筛选 -->
		<view class="filter-box">
			<view class="status-filter">
				<up-dropdown class="up-dropdown">
					<up-dropdown-item v-model="status" :title="statusTitle" :options="statusOptions" @change="onStatusChange"></up-dropdown-item>
				</up-dropdown>
			</view>
      <view class="new-btn">
        <u-button type="primary" text="批量新增" size="small" style="margin-right: 20rpx;" @click="onAddBatch()"></u-button>
        <u-button type="primary" text="新增" size="small" @click="onAddNew()"></u-button>
      </view>
		</view>

		<!-- 标签列表 -->
		<scroll-view class="label-list" scroll-y @scrolltolower="loadMore">
			<!-- 使用v-for循环渲染标签列表 -->
			<view class="label-item" v-for="(item, index) in labelList" :key="item.id">
				<view class="label-status" :class="getStatusClass(item.usage_status)">{{ item.usage_status_name }}</view>
				<view class="label-content">
					<view class="label-code">{{ item.label_code }}</view>
					<view class="label-info">
						<view class="info-item">标签规格: {{ item.label_specification }}</view>
						<view class="info-item">天线规格: {{ item.antenna_specification }}</view>
						<view class="info-item">芯片规格: {{ item.chip_specification }}</view>
						<view class="info-item">标签材质: {{ item.label_material }}</view>
					</view>
					<view class="label-actions">
						<text class="action-btn edit" @click="onEdit(item.id)">修改</text>
						<text class="action-btn unbind" @click="onUnbind(item.id)" v-if="item.usage_status === 'USED'">解绑</text>
						<text class="action-btn delete" @click="onDelete(item.id)" v-if="item.usage_status === 'NOT_USED'">报废</text>
					</view>
				</view>
			</view>
			
			<!-- 无数据提示 -->
			<view class="no-data" v-if="labelList.length === 0">
				<text>暂无数据</text>
			</view>
			
			<!-- 加载更多提示 -->
			<view class="loading-more" v-if="loading">
				<text>加载中...</text>
			</view>
			
			<!-- 没有更多数据提示 -->
			<view class="no-more" v-if="!loading && !hasMore && labelList.length > 0">
				<text>没有更多数据了</text>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import { ref, computed, onMounted, onUnmounted, watch, reactive } from 'vue';
	import http from "@/api/request";
	
	let searchRequestId = 0;
	// 数据定义
	const searchText = ref('');
	const status = ref('');
	
	// 创建响应式过滤条件对象
	const filterCondition = reactive({
		searchText: '',
		status: ''
	});
	
	// 分页相关状态
	const currentPage = ref(1);
	const pageSize = ref(10);
	const total = ref(0);
	const hasMore = ref(true);
	const loading = ref(false);
	
	// 监听搜索文本和状态变化，更新过滤条件
	watch(searchText, (newVal) => {
		filterCondition.searchText = newVal;
		resetPagination();
		getLabelList();
	});
	
	watch(status, (newVal) => {
		filterCondition.status = newVal;
		resetPagination();
		getLabelList();
	});
	
	const statusOptions = [
		{
			label: '全部',
			value: ''
		},
		{
			label: '已使用',
			value: 'USED'
		},
		{
			label: '未使用',
			value: 'NOT_USED'
		},
		{
			label: '报废',
			value: 'SCRAPPED'
		}
	];
	const labelList = ref([]);
	
	// 计算属性
	const statusTitle = computed(() => {
		if (!status.value) return '使用状态';
		const option = statusOptions.find(item => item.value === status.value);
		return option ? option.label : '使用状态';
	});
	
	// 生命周期钩子
	onMounted(() => {
		getLabelList();
	});
	
	// 重置分页状态
	function resetPagination() {
		currentPage.value = 1;
		hasMore.value = true;
		labelList.value = [];
	}
	
	// 加载更多数据
	function loadMore() {
		if (loading.value || !hasMore.value) return;
		currentPage.value++;
		getLabelList(true);
	}
	
	// 监听标签数据变化事件
	onMounted(() => {
		uni.$on('labelDataChanged', () => {
			console.log('标签数据已更改，重新加载列表');
			resetPagination();
			getLabelList();
		});
	});
	
	// 在组件卸载时移除事件监听
	onUnmounted(() => {
		uni.$off('labelDataChanged');
	});
	
	// 搜索框值变化事件
	function onSearchChange(value) {
		searchText.value = value;
		// watch会自动处理后续操作
	}
	
	// 状态筛选值变化事件
	function onStatusChange(value) {
		status.value = value;
		// watch会自动处理后续操作
	}
	
	// 获取状态对应的样式类
	function getStatusClass(status) {
		switch(status) {
			case 'USED':
				return 'used';
			case 'NOT_USED':
				return 'unused';
			case 'SCRAPPED':
				return 'scrapped';
			default:
				return '';
		}
	}
	
	// 方法定义
	// 获取标签列表
	function getLabelList(isLoadMore = false) {
		if (loading.value) return;
		const currentRequestId = ++searchRequestId;
		loading.value = true;
		
		console.log('查询条件:', filterCondition, '页码:', currentPage.value);
		
		// 构建请求参数
		const data = { 
			"pageCode": "rfidlabel", 
			"params": { 
				"args": [ 
					{ 
						"name": "interfaceCode", 
						"value": "rfidlabel.getPageList" 
					}, 
					{ 
						"name": "paging", 
						"value": JSON.stringify({"currentPage": currentPage.value, "pageSize": pageSize.value}) 
					}, 
					{ 
						"name": "filter", 
						"value": JSON.stringify(filterCondition.status ? {"usage_status": filterCondition.status} : {}) 
					} 
				] 
			}, 
			"methodName": "getPageList" 
		};
		
		// 如果有搜索文本，添加到过滤条件中
		if (filterCondition.searchText) {
			const filterObj = JSON.parse(data.params.args[2].value);
			filterObj.label_code = filterCondition.searchText;
			data.params.args[2].value = JSON.stringify(filterObj);
		}
		
		// 调用接口获取数据
		http.post("/api/module/Invoke", data).then((res) => {
			 // 只处理最新的请求
			if (currentRequestId !== searchRequestId) return;
			loading.value = false;
			
			if (res.result && res.result.data) {
				const newData = res.result.data || [];
				total.value = res.result.totalCount || 0;
				
				// 判断是否还有更多数据
				hasMore.value = labelList.value.length + newData.length < total.value;
				
				// 更新列表数据
				if (isLoadMore) {
					labelList.value = [...labelList.value, ...newData];
				} else {
					labelList.value = newData;
				}
			} else {
				uni.showToast({
					title: res.data?.message || '获取数据失败',
					icon: 'none'
				});
			}
		}).catch(err => {
		 if (currentRequestId !== searchRequestId) return;
			loading.value = false;
			console.error('获取标签列表失败:', err);
			uni.showToast({
				title: '网络异常，请稍后重试',
				icon: 'none'
			});
		});
	}

  const onAddBatch = () => {
    uni.navigateTo({
      url: '/pages/label/addBatch'
    })
  }
	
	// 新增标签
	function onAddNew() {
		uni.navigateTo({
			url: './add'
		});
	}
	
	// 修改标签
	// 修改标签
	function onEdit(id) {
		// 找到当前要编辑的标签数据
		const currentLabel = labelList.value.find(item => item.id === id);
		if (currentLabel) {
			uni.setStorageSync("assetLabel", currentLabel);
			// 跳转到编辑页面，并传递参数
			uni.navigateTo({
				url: `./edit`
			});
		} else {
			uni.showToast({
				title: '未找到标签数据',
				icon: 'none'
			});
		}
	}
	
	// 解绑标签
	function onUnbind(id) {
		uni.showModal({
			title: '提示',
			content: '确定要解绑此标签吗？',
			cancelText: '取消',
			confirmText: '确定',
			success: (res) => {
				if (res.confirm) {
					// 构建请求参数
					const data = { 
						"pageCode": "rfidlabel", 
						"params": { 
							"args": [ 
								{ 
									"name": "interfaceCode", 
									"value": "rfidlabel.updateUsageStatus" 
								}, 
								{ 
									"name": "params", 
									"value": JSON.stringify({"id": id, "type": 1}) 
								} 
							] 
						}, 
						"methodName": "updateUsageStatus" 
					};
					
					// 调用接口
					http.post("/api/module/Invoke", data).then((res) => {
						if (res.isSuccess) {
							uni.showToast({
								title: '解绑成功',
								icon: 'success'
							});
							// 刷新列表
							resetPagination();
							getLabelList();
						} else {
							uni.showToast({
								title: res.error || '解绑失败',
								icon: 'none'
							});
						}
					}).catch(err => {
						console.error('解绑标签失败:', err);
						uni.showToast({
							title: '网络异常，请稍后重试',
							icon: 'none'
						});
					});
				}
			}
		});
	}
	
	// 报废标签
	function onDelete(id) {
		uni.showModal({
			title: '提示',
			content: '确定要报废此标签吗？',
			cancelText: '取消',
			confirmText: '确定',
			success: (res) => {
				if (res.confirm) {
					// 构建请求参数
					const data = { 
						"pageCode": "rfidlabel", 
						"params": { 
							"args": [ 
								{ 
									"name": "interfaceCode", 
									"value": "rfidlabel.updateUsageStatus" 
								}, 
								{ 
									"name": "params", 
									"value": JSON.stringify({"id": id, "type": 2}) 
								} 
							] 
						}, 
						"methodName": "updateUsageStatus" 
					};
					
					// 调用接口
					http.post("/api/module/Invoke", data).then((res) => {
						if (res.isSuccess) {
							uni.showToast({
								title: '报废成功',
								icon: 'success'
							});
							// 刷新列表
							resetPagination();
							getLabelList();
						} else {
							uni.showToast({
								title: res.error || '报废失败',
								icon: 'none'
							});
						}
					}).catch(err => {
						console.error('报废标签失败:', err);
						uni.showToast({
							title: '网络异常，请稍后重试',
							icon: 'none'
						});
					});
				}
			}
		});
	}
</script>

<style>
	.search-box {
		margin-bottom: 20rpx;
	}

	.filter-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.status-filter {
		/* flex: 1; */
	}

	.status-filter :deep(.u-dropdown__menu) {
		justify-content: flex-start !important;
		padding-left: 0%;
		margin-left: 10rpx;
		width: 180rpx;
	}

	.status-filter :deep(.u-dropdown__title) {
		justify-content: flex-start !important;
		padding-left: 0;
		margin-left: 10rpx;
		width: 180rpx;
	}

	.new-btn {
		margin-left: 20rpx;
    display: flex;
    flex-direction: row;
	}

	.label-list {
		background-color: #fff;
		border-radius: 8rpx;
		height: calc(100vh - 200rpx); /* 设置高度以启用滚动 */
	}

	.label-item {
		display: flex;
		padding: 20rpx;
		border-bottom: 1px solid #eee;
	}

	.label-status {
		width: 100rpx;
		height: 40rpx;
		line-height: 40rpx;
		text-align: center;
		font-size: 24rpx;
		border-radius: 4rpx;
		margin-right: 20rpx;
	}

	.used {
		background-color: #e6f7ff;
		color: #1890ff;
	}

	.unused {
		background-color: #f0f9eb;
		color: #67c23a;
	}

	.scrapped {
		background-color: #fff2f0;
		color: #f56c6c;
	}

	.label-content {
		flex: 1;
	}

	.label-code {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.label-info {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 10rpx;
	}

	.info-item {
		font-size: 24rpx;
		color: #666;
		margin-right: 20rpx;
		margin-bottom: 10rpx;
	}

	.label-actions {
		display: flex;
	}

	.action-btn {
		font-size: 28rpx;
		margin-right: 30rpx;
	}

	.edit {
		color: #1890ff;
	}

	.unbind {
		color: #f56c6c;
	}

	.delete {
		color: #f56c6c;
	}

	.no-data {
		padding: 40rpx;
		text-align: center;
		color: #999;
		font-size: 28rpx;
	}

	.loading-more, .no-more {
		padding: 20rpx;
		text-align: center;
		color: #999;
		font-size: 24rpx;
	}
</style>